import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { AppPaginationComponent, PaginationModel } from "../../../../../widgets/pagination/pagination.component";
import { environment } from "../../../../../../environments/environment";
import * as _ from "lodash";
import { InputModeService } from './input-mode.service';
import { ApplyQDIINameComponent } from '../../modal/apply-qdiiname/apply-qdiiname.component';
import { DataService } from '../../../../../services/data.service';
import { Util } from '../../../../../common/util';
import { SelectItem } from 'primeng/components/common/api';
import { CommitComponent } from '../../modal/commit/commit.component';
@Component({
  selector: 'app-input-mode',
  templateUrl: './input-mode.component.html',
  styleUrls: ['./input-mode.component.scss'],
  providers: [InputModeService]
})
export class InputModeComponent implements OnInit {
  //判断当前listData类型,默认为false，代表空白20条数据，true为查询并填充之后的数组
  public listType: any = false;
  // 保存并提交modal
  @ViewChild("inputCommitModal", { read: ViewContainerRef })
  inputCommitModal: ViewContainerRef;
  commitComponent: ComponentRef<CommitComponent>;
  // 适用QDII名称modal
  @ViewChild("applyQDIIName", { read: ViewContainerRef })
  applyQDIIName: ViewContainerRef;
  applyQDIINameComponent: ComponentRef<ApplyQDIINameComponent>;
  public dictionaryInfo: SelectItem[];
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  //用于校验列表为空白10条或者查询填充列表
  public isBlank: any = true;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 分页列表post数据
  public postBody = {
    pageIndex: 1,
    pageSize: 50,
    nQdIdList: ''
  }
  public elementShow: any = [];
  //全选按钮
  public isCheckedAll: any = false;
  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //列表克隆数据
  public cloneList: any;
  //条目修改下拉框绑定数据
  public dataInfo: any = {
    pageIndex: 1,
    pageSize: 50,
    nQdIdList: '',
    sItemType: '',
    sFileSource: '',
    sFileName: '',
    sFundType: '',
    sFundGroupdsZh: '',
    sFundGroupds: '',
    f1: ''
  }
  //字典值列表
  public dictionaryList: any = {
    QDII_RECORD_TYPE: [],//属性
    NX_SOURCE: [],//条款出处
    QD_ACCOUNT_TYPE: [],//适用QDII类别
    RISK_BOOLMBERG_CONTROL: []//bloomberg系统能否控制    
  }
  //条目历史列表
  public listData: any = [
  ];
  constructor(
    public resolver: ComponentFactoryResolver,
    public inputModeService: InputModeService,
    public dataService: DataService
  ) { }

  //修改勾选的条目
  changeCheckedInfo(field) {
    let that = this;
    _.forEach(this.listData, (item, index) => {
      if (item.isChecked) {
        switch (field) {
          case 'sItemType':
            // item.sItemTypeZh = that.getValueByKey(that.dataInfo.sItemType, 'QDII_RECORD_TYPE')
            item.sItemType = that.dataInfo.sItemType;
            that.inputChange(index, item.sItemType, field)
            break;
          case 'sFileSource':
            // item.sFileSourceZh = that.getValueByKey(that.dataInfo.sFileSource, 'NX_SOURCE')
            item.sFileSource = that.dataInfo.sFileSource;
            that.inputChange(index, item.sFileSource, field)
            break;
          case 'sFileName':
            item.sFileName = that.dataInfo.sFileName;
            that.inputChange(index, item.sFileName, field)
            break;
          case 'sFundType':
            window['$']('#QDIIInputFundType' + index).selectpicker('val', that.dataInfo.sFundType);
            item.sFundType = that.dataInfo.sFundType;
            that.inputChange(index, item.sFundType, field)
            break;
          case 'sFundGroupdsZh':
            item.sFundGroupdsZh = that.dataInfo.sFundGroupdsZh;
            item.sFundGroupds = that.dataInfo.sFundGroupds;
            that.inputChange(index, item.sFundGroupdsZh, field)
            break;
          case 'f1':
            item.f1 = that.dataInfo.f1;
            that.inputChange(index, item.f1, field)
            break;
        }
      }
    })
  }
  //根据字典key查询value
  getValueByKey(key, dictionaryName) {
    let that = this;
    let info: any;
    // console.log(key)
    switch (dictionaryName) {
      case 'QDII_RECORD_TYPE':
        info = _.filter(that.dictionaryList.QDII_RECORD_TYPE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'NX_SOURCE':
        info = _.filter(that.dictionaryList.NX_SOURCE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'QD_ACCOUNT_TYPE':
        info = _.filter(that.dictionaryList.QD_ACCOUNT_TYPE, (item: any) => {
          return item.sItemKey == key
        })
        break;
      case 'RISK_BOOLMBERG_CONTROL':
        info = _.filter(that.dictionaryList.RISK_BOOLMBERG_CONTROL, (item: any) => {
          return item.sItemKey == key
        })
        break;
    }
    // console.log(info[0])
    return info[0].sItemValue;
  }
  //在指定位置新增一行
  addRow() {
    let checkedList: any = [];
    let indexList: any = [];
    _.forEach(this.listData, (item, index) => {
      indexList.push(index)
      if (item.isChecked) {
        checkedList.push(index);
      }
    })
    if (checkedList.length == 1) {
      let body: any = {
        sFileSource: "",//条款出处
        sFileName: "",//文件名称
        sItemType: "",//属性
        sFundType: [],//适用QDII类别
        sFundGroupds: "",//适用QDII名称
        sFundGroupdsZh: "",//适用QDII名称转义字段
        f1: "",//内容
        f3: "",//指标释义
        f4: "",//Bloomberg系统能否控制
        f5: "",//系统设置代码
        f6: "",//阀值
        f7: "",//人工控制方法说明
        f8: "",//系统实施相关条件
        f9: "",//备注1
        f10: ""//备注2
      }
      var sortedIndex = _.sortedIndex(indexList, checkedList[0]);
      this.listData.splice(sortedIndex + 1, 0, body);
      this.elementShow = _.cloneDeep(this.listData);
      console.log(sortedIndex)
      console.log(checkedList[0])
      console.log(indexList)
      console.log(this.listData)
      // Util.loadSelect(this.dictionaryList.QD_ACCOUNT_TYPE, 'selectpicker' + sortedIndex + 1)
      // window['$']('#selectpicker' + sortedIndex + 1).selectpicker('render');

    } else {
      window['swal']("提示", "请选择一条数据", "warning")
    }

  }
  //删除指定行
  delRow() {
    // this.listData = _.filter(this.listData, (item: any) => {
    //   return item.isChecked == false || item.isChecked == undefined;
    // })
    let that = this;
    let checkList: any = [];
    _.forEach(this.listData, (item: any) => {
      if (item.isChecked) {
        checkList.push(item)
      }
    })
    if (checkList.length != 0) {
      window['swal'](
        {
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: true,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否删除选中行" + "</div>",
          html: true
        }, function () {
          that.listData = _.filter(that.listData, (item: any) => {
            return item.isChecked == false || item.isChecked == undefined;
          })
        }
      );
    } else {
      window['swal']("提示", "请选择需要删除的行！", "warning")
    }
  }
  ngOnInit() {
    let that = this;
    // 初始化日期控件
    flatpickr.localize(zh);
    // 多选下拉框
    window['$'](".select2").select2();
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    Util.loadSelect(this.dictionaryList.QD_ACCOUNT_TYPE, 'QDIIInputFundType')

    this.dictionaryInfo = Util.loadPrimeSelect(this.dictionaryList.QD_ACCOUNT_TYPE);
    this.newList(10);
    this.cloneList = _.cloneDeep(this.listData)
    // console.log(JSON.stringify(this.cloneList))
    this.dataService.QDIIInputModelEmitter = new EventEmitter();
    this.dataService.QDIIInputModelEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'inputModel':
            that.dataInfo.sFundGroupdsZh = that.dataService.QDIINameList;
            that.dataInfo.sFundGroupds = that.dataService.QDIIIdList;
            that.changeCheckedInfo('sFundGroupdsZh');
            window['$']('#applyQDIIName').modal('hide');
            break;
          case 'index':
            that.listData[that.dataService.QDIIIndexId].sFundGroupdsZh = that.dataService.QDIINameList;
            that.listData[that.dataService.QDIIIndexId].sFundGroupds = that.dataService.QDIIIdList;
            window['$']('#applyQDIIName').modal('hide');
            break;
          case 'refreshInputList':
            if (that.listType) {
              that.loadlist();
            } else {
              that.newList(10);
            }
            break;
        }
      }
    })
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == 'QDII条目管理') {
                _.forEach(it.children, (ite, i) => {
                  if (ite.sName == '录入QDII条目') {
                    that.menuResourceSet = ite.resourceSet
                    sessionStorage.setItem('btn-QDII', this.menuResourceSet);
                  }
                })
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == 'QDII条目管理') {
            _.forEach(it.children, (ite, i) => {
              if (ite.sName == '录入QDII条目') {
                that.menuResourceSet = ite.resourceSet
                sessionStorage.setItem('btn-QDII', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
  }
  // ngAfterViewChecked() {
  //   for (let i = 0; i < this.listData.length; i++) {
  //     Util.loadSelect(this.dictionaryList.QD_ACCOUNT_TYPE, 'QDIIInputFundType' + i)
  //     // console.log("开始了")
  //     // console.log(this.dataInfo.sFundType)
  //     window['$']('#QDIIInputFundType' + i).selectpicker('val', this.listData[i].sFundType);
  //   }

  // }

  //添加10条空白数据进入列表
  newList(index) {
    this.listData = [];
    this.isBlank = true;
    for (let i = 0; i < index; i++) {
      this.listData.push({
        sFileSource: "",//条款出处
        sFileName: "",//文件名称
        sItemType: "",//属性
        sFundType: [],//适用QDII类别
        sFundGroupds: "",//适用QDII名称
        sFundGroupdsZh: "",//适用QDII名称转义字段
        f1: "",//内容
        f3: "",//指标释义
        f4: "",//Bloomberg系统能否控制
        f5: "",//系统设置代码
        f6: "",//阀值
        f7: "",//人工控制方法说明
        f8: "",//系统实施相关条件
        f9: "",//备注1
        f10: ""//备注2
      })
    }
    this.elementShow = _.cloneDeep(this.listData);
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  //展示保存并提交modal
  showModal() {
    window['$']('#reviewBack').modal('show');
  }
  //查询分页列表
  loadlist(pageNum?, pageSize?) {
    // console.log("loadList调用")
    let that = this;
    let listData = [];
    this.isCheckedAll = false;
    this.listType = true;
    this.isBlank = false;
    this.dataInfo.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.dataInfo.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.inputModeService.inputModeList(this.dataInfo).subscribe(data => {
      if (data) {
        this.listData = data.list;
        _.forEach(this.listData, it => {
          if (it.sFundType != null) {
            it.sFundType = it.sFundType.split(",");
          }
        })
        this.cloneList = _.cloneDeep(data.list)
        console.log(data);
        if (data.list.length > 0) {
          this.elementList(data.list.length);
        }
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
      }
    })
  }
  //批量录入-录入信息(保存按钮)
  save() {
    let that = this;
    let postBody: any = [];
    let listData = _.cloneDeep(this.listData)
    if (this.proofInfo()) {
      _.forEach(listData, item => {
        let isNull: any = true;
        if (item.isChecked) {
          delete item.isChecked;
          delete item.nQdId;
          delete item.sState;
          delete item.nBatchNo;
          delete item.sValid;
          delete item.auditOpr;
          delete item.auditOprDate;
          delete item.auditOprZh;
          delete item.commitOpr;
          delete item.commitOprDate;
          delete item.commitOprZh;
          _.forIn(item, (value, key) => {
            if (value != '' && value != null) {
              isNull = false;
            }
          })
          if (!isNull) {
            //判断选中的对象的sFundType是否为数组
            if (Array.isArray(item.sFundType)) {
              item.sFundType = item.sFundType.join(',');
            }
            postBody.push(item)
          }

        }
      })

      console.log(JSON.stringify(postBody))
      if (postBody.length == 0) {
        window['swal']("提示", "请选择需要操作的数据", "warning")
      } else {
        window['swal']({
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否录入选中的信息" + "</div>",
          html: true
        },
          function (isConfirm) {
            if (isConfirm) {
              that.inputModeService.save(postBody).subscribe(data => {
                if (data) {
                  window['swal']("提示", "录入信息成功", "success")
                  if (that.listType) {
                    that.loadlist();
                  } else {
                    that.newList(10);
                  }
                }
              })
            }
          })
      }
    }
  }
  //批量录入提交-保存提交(保存并提交按钮)
  submit() {
    let that = this;
    let postBody: any = [];
    let listData = _.cloneDeep(this.listData)
    if (this.proofInfo()) {
      _.forEach(listData, item => {
        let isNull: any = true;
        if (item.isChecked) {
          delete item.isChecked;
          delete item.nQdId;
          delete item.sState;
          delete item.nBatchNo;
          delete item.sValid;
          delete item.auditOpr;
          delete item.auditOprDate;
          delete item.auditOprZh;
          delete item.commitOpr;
          delete item.commitOprDate;
          delete item.commitOprZh;
          _.forIn(item, (value, key) => {
            if (value != '' && value != null) {
              isNull = false;
            }
          })
          if (!isNull) {
            //判断选中的对象的sFundType是否为数组
            if (Array.isArray(item.sFundType)) {
              item.sFundType = item.sFundType.join(',');
            }
            postBody.push(item)
          }
        }
      })
      console.log(JSON.stringify(postBody))
      if (postBody.length == 0) {
        window['swal']("提示", "请选择需要操作的数据", "warning")
      } else {
        this.showCommitModal(postBody)
      }
    }
  }
  //适用QDII名称modal
  showApplyQDIIName(index?) {
    // 判断组件是否已创建，如果创建先注销
    if (this.applyQDIINameComponent && this.applyQDIINameComponent.instance) {
      this.applyQDIINameComponent.destroy();
    }
    // 动态创建组件的实例
    const applyQDIINameComponent = this.resolver.resolveComponentFactory(ApplyQDIINameComponent);
    this.applyQDIINameComponent = this.applyQDIIName.createComponent(applyQDIINameComponent);
    if (index != null) {
      this.applyQDIINameComponent.instance.index = index;
      if (this.listData[index].sFundGroupdsZh != '' && this.listData[index].sFundGroupdsZh != null && this.listData[index].sFundGroupdsZh != undefined) {
        this.applyQDIINameComponent.instance.checkedIdList = this.listData[index].sFundGroupds.split(',');
        console.log(this.listData[index].sFundGroupds.split(','))
      }
    } else {
      this.applyQDIINameComponent.instance.modeType = 'input';
      if (this.dataInfo.sFundGroupdsZh != '' && this.dataInfo.sFundGroupdsZh != null && this.dataInfo.sFundGroupdsZh != undefined) {
        this.applyQDIINameComponent.instance.checkedIdList = this.dataInfo.sFundGroupds.split(',');
        console.log(this.dataInfo.sFundGroupds.split(','))
      }

    }

    window['$']('#applyQDIIName').modal('show');
  }
  //保存并提交modal
  showCommitModal(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.commitComponent && this.commitComponent.instance) {
      this.commitComponent.destroy();
    }
    // 动态创建组件的实例
    const commitComponent = this.resolver.resolveComponentFactory(CommitComponent);
    this.commitComponent = this.inputCommitModal.createComponent(commitComponent);
    this.commitComponent.instance.InputpostBody = item;
    this.commitComponent.instance.commitType = '录入模式';
    window['$']('#inputCommitModal').modal('show');
  }
  //校验录入模式保存或者保存并提交时必填的6个字段
  proofInfo() {
    let allInfoList: any = [];
    _.forEach(this.listData, (item, index) => {
      let checkInfo: any = [];
      let checkItem: any;
      if (item.isChecked) {
        if (item.sFileSource == null || item.sFileSource == '') {
          checkInfo.push('条款出处')
        }
        if (item.sFundType == null || item.sFundType == '') {
          checkInfo.push('适用QDII类别')
        }
        if (item.sItemType == null || item.sItemType == '') {
          checkInfo.push('属性')
        }
        if (item.sFileName == null || item.sFileName == '') {
          checkInfo.push('文件名称')
        }
        if (item.f1 == null || item.f1 == '') {
          checkInfo.push('内容')
        }
        if (item.sFundGroupdsZh == null || item.sFundGroupdsZh == '') {
          checkInfo.push('适用QDII名称')
        }
        if (checkInfo.length > 0) {
          checkItem = checkInfo.join('、');
          let math = index + 1;
          allInfoList.push('序号为' + math + '的数据' + checkItem + '字段不能为空</br>')

        }

      }
    })
    if (allInfoList.length > 0) {
      window['swal'](
        {
          type: "warning",
          confirmButtonText: "确认",
          closeOnConfirm: true,
          title: "提示",
          text: "<div style='max-height: 200px;overflow-y: auto;'>" + allInfoList.join(' ') + "</div>",
          html: true
        }, function () {

        }
      );
      return false;
    } else {
      return true;
    }
  }
  // 修改标蓝(i为下标,value为修改后的值,name为字段名)
  inputChange(i: any, value: any, name: any) {
    let that = this;
    //转义
    // console.log("value值:"+value);
    // console.log("name值"+name);
    if (that.listData[i].sItemType != '' && that.listData[i].sItemType != null && that.listData[i].sItemType != undefined) {
      this.listData[i].sItemTypeZh = this.getValueByKey(that.listData[i].sItemType, 'QDII_RECORD_TYPE')
    } else {
      this.listData[i].sItemTypeZh = '';
    }
    if (that.listData[i].f4 != '' && that.listData[i].f4 != null) {
      this.listData[i].f4Zh = this.getValueByKey(that.listData[i].f4, 'RISK_BOOLMBERG_CONTROL')
    } else {
      this.listData[i].f4Zh = '';
    }
    // 定位tr
    let index = i + 1;
    // 定位输入框和选择框
    let id = "#input-table tbody tr:nth-child(" + index + ") td div[id=" + name + "]";
    // let id2 = "#input-table tbody tr:nth-child(" + index + ") td select[name=" + name + "]";
    // 获取当前修改对象
    let item = this.cloneList[i];
    // 循环对象
    for (let key in item) {
      // 判断字段名是否相等
      if (key == name) {
        // 判断原值是否为null(后端空值返回null,前端空值为'',实际都为空,相等)
        if (item[key] == null) {
          if (value == '') {
            window['$'](id).removeClass('triangle-topleft');
          } else {
            window['$'](id).addClass('triangle-topleft');
          }
        } else {
          // 判断原值不为null,直接对比
          if (item[key] == value) {
            console.log("触发1")
            window['$'](id).removeClass('triangle-topleft');
          } else {
            console.log("触发2")
            window['$'](id).addClass('triangle-topleft');
          }
        }
      }
    }


  }
  //点击修改单元格字段状态
  changeEleStatus(index, field, type) {
    if (type == '1') {
      this.elementShow[index][field] = '1';
    } else {
      console.log("触发")
      this.elementShow[index][field] = '';
    }

  }
  //添加空白数据进入elementList
  elementList(index) {
    this.elementShow = [];
    for (let i = 0; i < index; i++) {
      this.elementShow.push({
        sFileSource: "",//条款出处
        sFileName: "",//文件名称
        sItemType: "",//属性
        sFundType: [],//适用QDII类别
        sFundGroupds: "",//适用QDII名称
        sFundGroupdsZh: "",//适用QDII名称转义字段
        f1: "",//内容
        f3: "",//指标释义
        f4: "",//Bloomberg系统能否控制
        f5: "",//系统设置代码
        f6: "",//阀值
        f7: "",//人工控制方法说明
        f8: "",//系统实施相关条件
        f9: "",//备注1
        f10: ""//备注2
      })
    }
  }
}
